import 'package:flutter/material.dart';
import '../utils/adapt.dart';
import '../utils/request.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';
import '../provider/playAudioList.dart';

class Singer extends StatefulWidget {
  var arguments;
  Singer({Key? key, this.arguments}) : super(key: key);

  @override
  _SingerState createState() => _SingerState(this.arguments);
}

class _SingerState extends State<Singer> with SingleTickerProviderStateMixin {
  var arguments;
  _SingerState(this.arguments);
  late TabController _tabController;
  ScrollController _scrollController = ScrollController();
  int _currentIndex = 1;
  @override
  void initState() {
    _tabController = TabController(
      initialIndex: 1,
      length: 5,
      vsync: this,
    );
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >
          _scrollController.position.maxScrollExtent - 40) {
        if (this._currentIndex == 1) {
          // 这里触底事件可以加载更多数据
        }
      }
    });
    super.initState();
    _getSongs(arguments['id']);
    this.setState(() {
      _topImg = arguments['picUrl'];
      _name = arguments['name'];
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  var _mes = '';
  var _name = '';
  var _topImg =
      'https://p2.music.126.net/BbR3TuhPULMLDV0MjczI4g==/109951165793869641.jpg';
  List _songList = [];
  void _getSongs(id) async {
    EasyLoading.show(status: 'loading...');
    var res = await getHttp('/artists?id=$id'); //歌手部分信息和热门歌曲
    EasyLoading.dismiss();
    this.setState(() {
      _mes = res['artist']['briefDesc'];
      _songList = res['hotSongs'];
    });
    _getMV(id, 1);
  }

  List _mvList = [];
  void _getMV(id, offset) async {
    EasyLoading.show(status: 'loading...');
    var res = await getHttp(
        '/artist/mv?id=$id&limit=20&offset=$offset'); //歌手部分信息和热门歌曲
    EasyLoading.dismiss();
    _getAlbum(id);
    this.setState(() {
      _mvList = res['mvs'];
    });
  }

  List _albumList = [];
  void _getAlbum(id) async {
    var res = await getHttp('/artist/album?id=$id&limit=30&offset=1');
    this.setState(() {
      _albumList = res['hotAlbums'];
    });
    _getSimilar(id);
  }

  List _similarSinger = []; // 相似歌手
  void _getSimilar(id) async {
    var res = await getHttp('/simi/artist?id=$id');
    this.setState(() {
      _similarSinger = res['artists'];
    });
  }

  @override
  Widget build(BuildContext context) {
    var playAudioList = Provider.of<PlayAudioList>(context);
    return Scaffold(
      body: NestedScrollView(
        controller: _scrollController,
        floatHeaderSlivers: true,
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverAppBar(
              title: Text(
                "$_name",
                style: TextStyle(fontSize: Adapt.px(30)),
              ),
              centerTitle: true,
              pinned: true,
              floating: true,
              expandedHeight: Adapt.px(600),
              flexibleSpace: FlexibleSpaceBar(
                background: Image.network(
                  _topImg + '?param=375y330',
                  fit: BoxFit.fill,
                ),
              ),
              bottom: TabBar(
                  indicatorColor: Colors.red,
                  labelColor: Colors.red,
                  unselectedLabelColor: Colors.white60,
                  labelPadding: const EdgeInsets.only(
                    bottom: 12,
                  ),
                  controller: _tabController,
                  isScrollable: false,
                  onTap: (index) {
                    this.setState(() {
                      _currentIndex = index;
                    });
                  },
                  tabs: [
                    Text(
                      "歌手简介",
                      style: TextStyle(fontSize: Adapt.px(26)),
                    ),
                    Text(
                      "流行单曲",
                      style: TextStyle(fontSize: Adapt.px(26)),
                    ),
                    Text(
                      "时尚MV",
                      style: TextStyle(fontSize: Adapt.px(26)),
                    ),
                    Text(
                      "专辑",
                      style: TextStyle(fontSize: Adapt.px(26)),
                    ),
                    Text(
                      "相似歌手",
                      style: TextStyle(fontSize: Adapt.px(26)),
                    ),
                  ]),
            ),
          ];
        },
        body: TabBarView(
          controller: _tabController,
          children: [
            _mes == '' ? Text('') : TabA(_mes),
            _songList.length == 0 ? Text("") : SongList(_songList),
            _mvList.length == 0 ? Text("") : MVList(_mvList),
            _albumList.length == 0 ? Text("") : Album(_albumList),
            _similarSinger.length == 0 ? Text("") : Similar(_similarSinger),
          ],
        ),
      ),
    );
  }
}

class TabA extends StatelessWidget {
  String _text;
  TabA(this._text);
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(Adapt.px(20)),
      child: Text(
        "$_text",
        style: TextStyle(fontSize: Adapt.px(40), height: 1.5),
      ),
    );
  }
}

class SongList extends StatefulWidget {
  List _list;
  SongList(this._list, {Key? key}) : super(key: key);

  @override
  _SongListState createState() => _SongListState(this._list);
}

class _SongListState extends State<SongList> {
  List _list;
  _SongListState(this._list);
  void _goPlay() {
    Navigator.pushNamed(context, "/audioplayer", arguments: {});
  }

  @override
  Widget build(BuildContext context) {
    var playAudioList = Provider.of<PlayAudioList>(context);
    return ListView.separated(
      padding: EdgeInsets.symmetric(horizontal: 0),
      itemCount: _list.length,
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          height: 1,
          color: Colors.grey,
        );
      },
      itemBuilder: (BuildContext context, int index) {
        return ListTile(
          onTap: () {
            var newList = _list
                .map((item) => {
                      "id": item['id'],
                      "name": item['name'],
                      "picUrl": item['al']['picUrl']
                    })
                .toList();
            playAudioList.setCurrentIndex(index);
            playAudioList.setAudioList(newList);
            _goPlay();
          },
          leading: Image.network(
            _list[index]['al']['picUrl'] + '?param=80y80',
            width: Adapt.px(80),
          ),
          title: Text(
            _list[index]['name'],
            style: TextStyle(fontSize: Adapt.px(26)),
          ),
          trailing: Icon(Icons.play_circle_filled_outlined),
        );
      },
    );
  }
}

class MVList extends StatefulWidget {
  List _list;
  MVList(this._list, {Key? key}) : super(key: key);

  @override
  _MVListState createState() => _MVListState(this._list);
}

class _MVListState extends State<MVList> {
  List _list;
  _MVListState(this._list);
  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
        childAspectRatio: 16 / 12,
        mainAxisSpacing: 2,
        crossAxisSpacing: 2,
        maxCrossAxisExtent: 200,
      ),
      itemCount: _list.length,
      padding: EdgeInsets.symmetric(vertical: 0, horizontal: Adapt.px(20)),
      itemBuilder: (BuildContext context, int index) {
        return Container(
          color: Colors.grey[100],
          child: Column(
            children: [
              InkWell(
                onTap: () {
                  var dataObj = _list[index];
                  Navigator.pushNamed(context, "/videoplayer", arguments: {
                    "vid": dataObj['id'],
                    "cover": dataObj['imgurl16v9'],
                    "name": dataObj['name'],
                    "desc": "",
                    "artistName": dataObj['artistName'],
                  });
                },
                child: Container(
                  width: double.infinity,
                  height: Adapt.px(200),
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      AspectRatio(
                        aspectRatio: 1.78 / 1,
                        child: Image.network(
                          _list[index]['imgurl16v9'] + "?param=160y90",
                          width: double.infinity,
                        ),
                      ),
                      Icon(
                        Icons.play_circle_outline,
                        size: Adapt.px(80),
                      )
                    ],
                  ),
                ),
              ),
              Text(
                _list[index]['name'],
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(height: 1.5, fontSize: Adapt.px(26)),
              ),
            ],
          ),
        );
      },
    );
  }
}

class Album extends StatefulWidget {
  //专辑
  List _list = [];
  Album(this._list, {Key? key}) : super(key: key);

  @override
  _AlbumState createState() => _AlbumState(this._list);
}

class _AlbumState extends State<Album> {
  List _list;
  _AlbumState(this._list);
  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      padding: EdgeInsets.symmetric(horizontal: 0),
      itemCount: _list.length,
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          height: 1,
          color: Colors.grey,
        );
      },
      itemBuilder: (BuildContext context, int index) {
        return ListTile(
          onTap: () {
            Navigator.pushNamed(context, "/album",
                arguments: {"albumId": _list[index]['id']});
          },
          leading: Image.network(
            _list[index]['picUrl'] + '?param=80y80',
            width: Adapt.px(100),
          ),
          title: Text(
            _list[index]['name'],
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(height: 1.5, fontSize: Adapt.px(26)),
          ),
          trailing: Icon(Icons.list_alt_sharp),
        );
      },
    );
  }
}

class Similar extends StatefulWidget {
  List _list;

  Similar(this._list, {Key? key}) : super(key: key);

  @override
  _SimilarState createState() => _SimilarState(this._list);
}

class _SimilarState extends State<Similar> {
  List _list;
  _SimilarState(this._list);
  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      padding: EdgeInsets.symmetric(horizontal: 0),
      itemCount: _list.length,
      separatorBuilder: (BuildContext context, int index) {
        return Divider(
          height: 1,
          color: Colors.grey,
        );
      },
      itemBuilder: (BuildContext context, int index) {
        return ListTile(
          onTap: () {
            Navigator.pushReplacementNamed(context, '/singer', arguments: {
              "name": _list[index]['name'],
              "picUrl": _list[index]['picUrl'],
              "id": _list[index]['id']
            });
          },
          leading: Image.network(
            _list[index]['img1v1Url'] + '?param=80y80',
            width: Adapt.px(100),
          ),
          title: Text(
            _list[index]['name'],
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(height: 1.5, fontSize: Adapt.px(26)),
          ),
          trailing: Icon(Icons.list_alt_sharp),
        );
      },
    );
  }
}
